package com.example.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.dao.BookDao;
import com.example.dao.OtherDao;
import com.example.dao.TypeDao;
import com.example.entity.Book;
import com.example.entity.Other;
import com.example.entity.Params;
import com.example.entity.Type;
import com.example.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 日期：2025/5/11 19:57
 */

@Service
public class OtherService {

    @Resource
    private OtherDao otherDao;
    @Resource
    private TypeDao typeDao;


    public PageInfo<Other> findBySearch(Params params) {
        //        开启分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
//        接下来的查询会自动按照当前开启的分页设置来查询
        List<Other> list = otherDao.findBySearch(params);
        if(CollectionUtil.isEmpty(list)){
            return PageInfo.of(new ArrayList<>());
        }
        for (Other other : list) {
            if (ObjectUtil.isNotEmpty(other.getTypeId())) {
                Type type = typeDao.selectByPrimaryKey(other.getTypeId());
                if (ObjectUtil.isNotEmpty(type)) {
                    other.setTypeName(type.getName());
                }
            }
        }
        return PageInfo.of(list);
    }

    public void add(Other other) {
        if(other.getName() == null ||
                other.getNum() == null ||
                other.getPrice() == null ||
                other.getTypeId() == null ||
                other.getAuthor() == null ||
                other.getPress() == null){
            throw new CustomException("内容不能为空");
        }
        otherDao.insertSelective(other);
    }

    public void update(Other other) {
        otherDao.updateByPrimaryKeySelective(other);
    }

    public void delete(Integer id) {
        otherDao.deleteByPrimaryKey(id);
    }

    public List<Other> findAll() {
        return otherDao.findAll();
    }
}
